require 'digest/sha2'
class Usuario < ActiveRecord::Base

  validates_uniqueness_of :usuario
  
  attr_accessor :contrasena
  
  def before_create
    self.secreto = self.contrasena
  end
  
  def before_update
    self.secreto = self.contrasena
  end
  
  def secreto=(pass)
    salt = [Array.new(6){rand(256).chr}.join].pack("m" ).chomp
    self.password_salt, self.password_hash = salt, Digest::SHA256.hexdigest(pass + salt)
  end
  
  def self.authenticate(username, password)
    user = Usuario.find(:first, :conditions => ['usuario = ?' , username])
    if user.blank? ||
      Digest::SHA256.hexdigest(password + user.password_salt) != user.password_hash
      raise "Usuario o Password Invalido..."
    end
    user
  end

end
